import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login'
import Register from '@/views/Register'
import Detail from '@/views/Detail'
import Layout from '@/views/Layout'
import Like from '@/views/Like'
import Article from '@/views/Article'
import Collect from '@/views/Collect'
import User from '@/views/User'
import { getToken } from '@/utils/storage'

Vue.use(VueRouter)

const routes = [
  // 一级路由
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  { path: '/article/:id', component: Detail },
  {
    path: '/',
    component: Layout,
    // 重定向
    redirect: '/article',
    children: [
      // 二级路由
      { path: 'article', component: Article },
      { path: 'like', component: Like },
      { path: 'collect', component: Collect },
      { path: 'user', component: User }
    ]
  }
]

const router = new VueRouter({
  routes
})

const whiteList = ['/login', 'register']
router.beforeEach((to, from, next) => {
  const token = getToken()
  // 如果有token，直接放行
  if (token) {
    next()
  } else {
    // 没有token的人, 看看你要去哪
    // (1) 访问的是无需授权的页面（白名单），也是放行
    //     就是判断，访问的地址，是否在白名单数组中存在 includes
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // (2) 否则拦截到登录
      next('/login')
    }
  }
})

export default router
